package csc.fresher.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import csc.fresher.bankservice.BankService;
import csc.fresher.domain.History;
import csc.fresher.domain.UserInfo;

/**
 * After login success. Save time login to table History. And redirect to home
 * page
 * 
 *
 */
@Component
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private BankService services;

	public static int idHistory;

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse respone, Authentication arg2) throws IOException,
			ServletException {
		// get User login
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String loginId = auth.getName();
		UserInfo user = services.getUserInfo(loginId);
		
		History history = new History(user, new Date());
		
		// get Id identity after add to table
		int id = services.addHistory(history);
		idHistory = id;
		
		if(user.getImage() != null){
			byte[] encode = Base64.encode(user.getImage());
			String avatar = new String(encode);
			request.getSession().setAttribute("avatar", avatar);
		}
		
		// redirect to homepage
		redirectStrategy.sendRedirect(request, respone, "/");
	}
}
